package com.aicoq.example.stock.service.impl;

import com.aicoq.example.stock.domain.StockDayInfoDto;
import com.aicoq.example.stock.domain.SyncCategoryRelRequest;
import com.aicoq.example.stock.persist.mapper.StockCategoryMapper;
import com.aicoq.example.stock.persist.mapper.StockCategoryRelMapper;
import com.aicoq.example.stock.persist.model.*;
import com.aicoq.example.stock.persist.model.example.StockCategoryExample;
import com.aicoq.example.stock.persist.model.example.StockCategoryRelExample;
import com.aicoq.example.stock.service.StockCategoryRelService;
import com.aicoq.example.utils.http.OkHttpUtils;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class StockCategoryRelServiceImpl implements StockCategoryRelService {

    @Autowired
    private StockCategoryMapper stockCategoryMapper;
    @Autowired
    private StockCategoryRelMapper stockCategoryRelMapper;

    private final static Logger logger = LoggerFactory.getLogger(StockCategoryRelServiceImpl.class);

    private final static int PAGE_SIZE = 40;

    @Override
    public void syncCategoryRel(SyncCategoryRelRequest request) {
        var categoryList = categoryKeyList(request.getCategoryKeyList(), request.getHotFlag());
        var executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            for (var market : categoryList) {
                saveSyncStockMarket(market);
            }
            logger.info("跑完了");
        });
    }

    private void saveSyncStockMarket(StockCategory category) {
        int page = 1;
        while (true) {
            var stockInfoList = queryStockFromSina(category.getCategoryKey(), page++);
            if (stockInfoList == null) {
                break;
            }
            for (var stock : stockInfoList) {
                StockCategoryRelExample queryStockCategoryRelExample = new StockCategoryRelExample();
                queryStockCategoryRelExample.createCriteria()
                        .andCategoryIdEqualTo(category.getCategoryId())
                        .andSymbolEqualTo(stock.getSymbol());
                if (stockCategoryRelMapper.countByExample(queryStockCategoryRelExample) == 0) {
                    StockCategoryRel saveCategoryRel = new StockCategoryRel();
                    saveCategoryRel.setCategoryId(category.getCategoryId());
                    saveCategoryRel.setSymbol(stock.getSymbol());
                    stockCategoryRelMapper.insertSelective(saveCategoryRel);
                }
            }
            if (stockInfoList.size() < PAGE_SIZE) {
                break;
            }
            sleep();
        }
    }

    private void sleep() {
        try {
            TimeUnit.SECONDS.sleep(new Random().nextLong(10L));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private List<StockDayInfoDto> queryStockFromSina(String category, int page) {
        var url = "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=%d&num=%s&sort=symbol&asc=1&node=%s&symbol=&_s_r_a=init";
        var formatUrl = String.format(url, page, PAGE_SIZE, category);
        var result = OkHttpUtils.get(formatUrl);
        return JSON.parseArray(result, StockDayInfoDto.class);
    }


    private List<StockCategory> categoryKeyList(List<String> categoryKeyList, int hotFlag) {

        StockCategoryExample queryCategoryExample = new StockCategoryExample();
        StockCategoryExample.Criteria criteria = queryCategoryExample.createCriteria()
                .andHotFlagGreaterThanOrEqualTo(hotFlag);
        if (categoryKeyList!=null && !categoryKeyList.isEmpty()) {
            criteria.andCategoryKeyIn(categoryKeyList);
        }
        List<StockCategory> stockCategoryList = stockCategoryMapper.selectByExample(queryCategoryExample);
        if (stockCategoryList.isEmpty()) {
            return Lists.newArrayList();
        }
        return stockCategoryList;
    }

}
